<template>
  <div>
    <!-- 搜索框部分 -->
    <form action="/">
      <van-search v-model="sval" show-action @search="onSearch" @cancel="onCancel" style="position:fixed;top:0vh;left:0vw;width:100vw;z-index:1; border-radius: 8px; border: 1px solid #ccc; padding: 8px;" />
    </form>

    <!-- 地址信息部分 -->
    <div class="location-container" style="margin-top: 56px;">
      <!-- 基准地址 -->
      <div class="base-location">
        <div class="location-title">
          <div class="location-value">基准地址</div>
        </div>
        <div class="location-address">
          {{ baseAddress }}
        </div>
        <img class="location-icon" :src="require('@/assets/loc.png')" @click="showMap" />
      </div>

      <!-- 附近距离 -->
      <div class="nearby">
        <span class="location-title">附近</span>
        <div class="van-f">
          <van-field input-align="right" type="number" maxlength="2" center clearable v-model="distance" placeholder="请输入内容" @keypress.enter="handleSubmit" ref="myInputField"></van-field>
          <div class="unit">公里</div>
        </div>

      </div>
    </div>

    <!-- 列表部分 -->
    <div class="container">
      <div class="list-container">
        <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
          <van-list v-model="loading" :finished="finished" finished-text="已加载全部数据" @load="onLoad">
            <van-checkbox-group v-model="selecteddata" ref="checkboxGroup">
              <van-cell v-for="(item, index) in list" :key="item.id" :value="item.value" @click="toggle(index)" style="padding: 15px 10px; border-bottom: 1px solid #eee;">
                <van-checkbox :name="item" ref="checkboxes" slot="right-icon" />
                <template #title>
                  <span style="font-size: 16px; color: #333;">{{ item.title }}</span><br>
                  <span style="font-size: 12px;color: #999;" v-html="item.label"></span>
                </template>
              </van-cell>
            </van-checkbox-group>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
    <!--    <div v-if="isModalVisible" class="modal-overlay" @click="closeMapModal">-->

    <div v-if="isModalVisible" class="modal-overlay">
      <div class="modal-content">
        <div id="map" v-if="isMapLoaded" style="width: 100%; height: 400px;"></div>
      </div>
    </div>

    <!-- 添加按钮 -->
    <div class="add-image" v-if="showadd">
      <img :src="require('@/assets/add.png')" @click="openNew" />
    </div>

    <!-- 底部确定按钮 -->
    <van-tabbar>
      <van-tabbar-item @click="reBack()">确定</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import Vue from 'vue'
import {
  Search,
  List,
  Cell,
  PullRefresh,
  Toast,
  Tabbar,
  TabbarItem,
  Popup,
  CheckboxGroup,
  Checkbox,
  Button
} from 'vant'
import qs from 'qs'
import * as dd from 'dingtalk-jsapi'
import wx from 'weixin-js-sdk'
import Utils from '@/utils/utils'
import YYEsnBridge from '@/assets/js/esn.min.js'
Vue.use(Search)
  .use(List)
  .use(Cell)
  .use(PullRefresh)
  .use(Toast)
  .use(Tabbar)
  .use(TabbarItem)
  .use(Popup)
  .use(CheckboxGroup)
  .use(Checkbox)
  .use(Button)

export default {
  name: 'Refmulti4Account',
  data () {
    return {
      sval: this.$route.params.conditionVal,
      list: [],
      loading: false,
      finished: false,
      isLoading: false,
      startline: 1,
      selecteddata: [],
      baseAddress: '',
      distance: 1,
      center: [116.417755, 40.069894],
      isModalVisible: false,
      isMapLoaded: false, // 控制地图是否加载
      map: null,
      marker: null,
      // 是否显示添加按钮
      showadd: true,
      infoWindow: null,
      ref4Account: 'true'
    }
  },
  created: function () {
    let ua = window.navigator.userAgent.toLowerCase()
    //console.log(ua)
    let logintype = 'wechat'
    let tourl = window.location.href
    let clttype = 'android'

    if (ua.indexOf('wxwork') !== -1) {
      logintype = 'wxwork'
    } else if (ua.indexOf('dingtalk') !== -1) {
      logintype = 'dingding'
    } else if (ua.indexOf('micromessenger') !== -1) {
      logintype = 'wechat'
    } else {
      logintype = 'browser'
    }
    if (logintype === 'browser') {
      // Toast('请在钉钉或微信端登录!')
      // this.$router.go(-1)
    }
    if (ua.indexOf('iphone') !== -1) {
      clttype = 'ios'
    }
    let _this = this
    let data = {
      url: tourl,
      type: logintype,
      clttype: clttype
    }
    let url = '/api/' + this.idobject + '.getlocation.do'
    this.axios({
      method: 'post',
      url: url,
      data: qs.stringify(data)
    }).then(res => {
      if (res.data.flag === '1' && res.data.des && res.data.des.indexOf('登录过期') >= 0) {
        Toast(res.data.des)
        this.loginout()
      } else {
        let data = res.data
        if (logintype === 'wechat' || logintype === 'wxwork') {
          wx.config({
            beta: true,
            debug: false,
            appId: data.appId,
            timestamp: data.timestamp,
            nonceStr: data.nonceStr,
            signature: data.signature,
            jsApiList: [
              'getLocation'
            ]
          })
          wx.ready(function () {
            wx.getLocation({
              isHighAccuracy: true,
              type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
              success: function (res) {
                var latitude = res.latitude // 纬度，浮点数，范围为90 ~ -90
                var longitude = res.longitude // 经度，浮点数，范围为180 ~ -180。
                this.center[0] = res.longitude
                this.center[1] = res.latitude

                // 逆地理编码获取位置名称
                wx.reverseGeoCode({
                  latitude: latitude,
                  longitude: longitude,
                  success (res) {
                    this.baseAddress = res.address // 位置的名称
                  },
                  fail (err) {
                    console.error(err)
                  }
                })
              },
              cancel: function (res) {
                Toast('请打开企业微信的定位权限再重试!')
              },

              fail: function (res) {
                Toast('faled: ' + JSON.stringify(res))
              }
            })
          })
        } else if (logintype === 'dingding') {
          dd.config({
            agentId: data.agentid,
            corpId: data.appId,
            timeStamp: data.timestamp,
            nonceStr: data.nonceStr,
            signature: data.signature,
            type: 0,
            jsApiList: [
              'runtime.info',
              'biz.contact.choose',
              'device.notification.confirm',
              'device.notification.alert',
              'device.notification.prompt',
              'biz.ding.post',
              'biz.util.openLink',
              'device.geolocation.get'
            ]
          })
          dd.error((error) => {
            Toast('dd error: ' + JSON.stringify(error))
          })
          dd.ready(() => {
            dd.device.geolocation.get({
              targetAccuracy: 200,
              coordinate: 1,
              withReGeocode: true,
              useCache: true,
              onSuccess: (res) => {
                this.center[0] = res.longitude
                this.center[1] = res.latitude
                this.baseAddress = res.address
                // Toast('res:' + JSON.stringify(res), { duration: 10000 })
              },
              onfail: (err) => {
                Toast('err' + err)
              }
            })
          })
        } else {
          // 不做处理
        }
      }
    }).catch((error) => {
      Toast('error' + error)
    })
  },
  methods: {
    handleSubmit () {
      // 使用 blur() 方法移除焦点
      this.$refs.myInputField.$el.querySelector('input').blur()
      // 输入公里后重新刷新列表
      this.onRefresh()
    },
    closeMapModal () {
      //console.log('close')
      this.showadd = true
      this.isModalVisible = false
      if (this.map) {
        this.map.destroy() // 释放地图资源
      }
    },
    showMap () {
      //console.log('showmap')
      this.isModalVisible = true
      this.loadMap() // 点击按钮时加载地图
      this.showadd = false
    },
    loadMap () {
      // 加载高德地图API
      const script = document.createElement('script')
      script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=e762e8d8003a79d26ece5f84b4afbfb0'
      script.async = true
      script.onload = () => {
        this.initMap() // 加载地图后初始化
      }
      document.head.appendChild(script)
      this.isMapLoaded = true // 设置地图加载状态
    },
    initMap () {
      // 初始化高德地图
      this.map = new AMap.Map('map', {
        zoom: 14,
        center: this.center // 默认中心点
      })

      this.map.on('complete', () => {
        this.getAddress(this.center[0], this.center[1])
      })

      // 监听地图点击事件
      this.map.on('click', (event) => {
        const longitude = event.lnglat.getLng()
        const latitude = event.lnglat.getLat()
        this.center = [longitude, latitude]
        this.map.remove(this.marker)
        this.getAddress(longitude, latitude) // 获取地址
      })
    },
    getAddress (longitude, latitude) {
      // 使用高德API的地理编码服务获取地址
      AMap.service(['AMap.Geocoder'], () => {
        const geocoder = new AMap.Geocoder({
          // city: '北京' // 省市名称
        })

        geocoder.getAddress([longitude, latitude], (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            this.baseAddress = result.regeocode.formattedAddress // 获取格式化地址
            //console.log('this.baseAddress', this.baseAddress)
            this.marker = new AMap.Marker({
              position: this.center
            })
            this.marker.setMap(this.map)
            this.showInfoWindow(longitude, latitude, this.baseAddress) // 显示信息窗口
          } else {
            console.error('获取地址失败', result)
          }
        })
      })
    },

    showInfoWindow (longitude, latitude, address) {
      var title = ''
      var content = []
      const text = `<div class="content" style=''><p>${address}</p><div><button class="navigation" style='' >确定</button></div></div>`
      content.push(text)
      var infoWindow = new AMap.InfoWindow({
        isCustom: true, // 使用自定义窗体
        content: this.createInfoWindow(title, content.join('<br/>')),
        offset: new AMap.Pixel(16, -45)
      })

      infoWindow.open(this.map, this.center)

      // 绑定确定按钮的点击事件
      // this.bindConfirmButton()
    },

    // 构建自定义信息窗体
    createInfoWindow (title, content) {
      var info = document.createElement('div')
      info.className = 'custom-info input-card content-window-card'

      // 可以通过下面的方式修改自定义窗体的宽高
      // info.style.width = "400px";
      // 定义顶部标题
      var top = document.createElement('div')
      var titleD = document.createElement('div')
      // var closeX = document.createElement('img')
      top.className = 'info-top'
      titleD.innerHTML = title
      // closeX.src = 'https://webapi.amap.com/images/close2.gif'
      // closeX.onclick = closeInfoWindow

      top.appendChild(titleD)
      // top.appendChild(closeX)
      info.appendChild(top)

      // 定义中部内容
      var middle = document.createElement('div')
      middle.className = 'info-middle'
      // middle.style.backgroundColor = 'white';
      middle.innerHTML = content
      info.appendChild(middle)

      // 定义底部内容
      var bottom = document.createElement('div')
      bottom.className = 'info-bottom'
      bottom.style.position = 'relative'
      bottom.style.top = '0px'
      bottom.style.margin = '0 auto'
      var sharp = document.createElement('img')
      sharp.src = 'https://webapi.amap.com/images/sharp.png'
      bottom.appendChild(sharp)
      info.appendChild(bottom)
      info.addEventListener('click', (event) => {
        if (event.target && event.target.classList.contains('navigation')) {
          this.confirmAct()
        }
      })

      return info
    },
    bindConfirmButton () {
      // 使用 setTimeout 确保按钮元素已被添加到 DOM 中
      setTimeout(() => {
        const confirmButton = document.getElementById('confirm-button')
        if (confirmButton) {
          confirmButton.onclick = () => {
            this.infoWindow.close() // 点击确定后关闭信息窗口
            this.closeMapModal()
            // 地图点击后重新刷新列表
            this.onRefresh()
          }
        }
      }, 0)
    },

    confirmAct () {
      this.closeMapModal()
      // 地图点击后重新刷新列表
      this.onRefresh()
    },

    onLoad () {
      let data = {
        'ref_object': this.$route.params.bo,
        'ref_toobject': this.$route.params.tobo,
        'ref_tofieldas': this.$route.params.field,
        'ref_inview': this.$route.params.conditionValHidden,
        'view_page': this.startline,
        'view_id': this.$route.params.viewid,
        'ref_wd': this.center[1],
        'ref_jd': this.center[0],
        'ref_km': this.distance,
        'ref_ref4account': 'true'
      }
      //console.log('data', data)

      data.ref_inview = data && data.ref_inview && data.ref_inview.replace(':in:', ':in:' + this.sval)

      this.axios({
        method: 'post',
        url: '/api/ref.listnew.do',
        data: qs.stringify(data)
      }).then(res => {
        if (res.data.flag === '1') {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          }
        } else {
          let rsdata = res.data.jsondata.outdata
          for (let i = 0; i < rsdata.length; i++) {
            this.list.push(rsdata[i])
          }
          if (rsdata == null || rsdata.length === 0) {
            this.loading = false
            this.finished = true
          } else {
            this.startline = this.startline + 1
            this.loading = false
          }
        }
      }).catch(res => {
        this.reserror(res)
      })
    },
    onRefresh () {
      this.list = []
      this.startline = 1
      this.isLoading = false
      this.loading = true
      this.finished = false
      this.onLoad()
    },
    openNew () {
      this.$router.push({
        name: 'new',
        query: {
          idobject: this.$route.params.bo,
          newflag: 'refnew',
          reBackflag: this.rebackobject
        }
      })
    },
    onSearch () {
      this.list = []
      this.startline = 1
      this.onLoad()
    },
    onCancel () {
      this.sval = ''
      this.$router.go(-1)
    },
    toggle (index) {
      this.$refs.checkboxes[index].toggle()
    },
    reBack () {
      let refid = ''
      let refval = ''

      if (this.$route.params.tobo == 'bflxmx' || this.$route.params.tobo === 'jhglmx') {
        let refArr = this.selecteddata
        let payload = { ref_arr: refArr }
        this.$store.commit('refReBack', payload)
        this.$router.go(-1)
        return
      }

      for (let i = 0; i < this.selecteddata.length; i++) {
        refid += this.selecteddata[i].id + ';'
        refval += this.selecteddata[i][this.$route.params.fieldref] + ';'
      }

      let payload = {
        ref_id: refid,
        ref_show: refval,
        ref_field: this.$route.params.field,
        ref_item: this.selecteddata[0]
      }
      this.$store.commit('refReBack', payload)
      this.$router.go(-1)
    }
  }
}
</script>

<style>
.location-container {
  padding: 16px 16px 0 16px;
  margin: 0 auto;
  background: #fff;
}

.base-location {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.location-title {
  font-family: "Microsoft YaHei Bold";
  font-weight: 700;
  font-size: 16px;
  text-align: left;
  color: #000;
}

.location-icon {
  /*margin-left: 8px;*/
}

.location-address {
  font-family: "Microsoft YaHei";
  font-weight: 400;
  font-size: 14px;
  line-height: 14px;
  text-align: left;
  color: #000;
  margin: 0 16px;
}

.van-f {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.unit {
  min-width: 32px;
}

.location-value {
  min-width: 64px;
}

.nearby {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  justify-content: space-between;
  color: #666;
}

.container {
  padding: 0 20px 20px 20px;
}

.list-container {
  max-height: calc(100vh - 250px);
  overflow-y: auto;
  padding: 10px;
}

.add-image {
  position: fixed;
  right: 5px;
  bottom: 80px;
  z-index: 1000;
}

.add-image img {
  width: 75px;
  height: auto;
  border-radius: 50%;
}

.van-tabbar {
  display: flex;
  justify-content: center;
  padding-bottom: 15px !important;
}

.van-tabbar .van-tabbar-item {
  color: white;
  background-color: #5790df !important;
  width: 80% !important;
  flex: 0 0 80% !important;
  font-size: 14px;
}

.van-cell .van-cell__title {
  flex: 2 !important;
}

.van-cell .van-cell__value {
  flex: 1 !important;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  width: 80%;
  max-width: 600px;
}

.custom-button {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 10px;
  border-radius: 5px;
  cursor: pointer;
  width: 300px;
}

.content-window-card {
  padding: 3px;
  width: 80vw;
}

div.info-top {
  display: flex;
  justify-content: flex-end;
  flex-direction: row;
  background-color: rgba(54, 56, 57, 0.8);
}

div.info-top img {
  display: none;
}

div.info-middle {
  padding: 5px 13px;
  border-radius: 14px;
  background-color: rgba(54, 56, 57, 0.8);
}

div.info-bottom img {
  position: absolute;
  left: 150px;
}

.content {
  display: flex;
  justify-content: center;
  align-items: center;
}

.content p {
  flex: 6;
  margin: 0;
  padding: 0;
  color: #fff;
}

.content div {
  flex: 2;
}

.navigation {
  width: 70px;
  height: 30px;
  /* background-color: rgb(63, 143, 255); */
  background-color: #3385ff;
  border-radius: 10px;
  border: none;
  letter-spacing: 2px;
  color: #fff;
}
</style>
